package com.yvdedu.hospital.shiro;

import java.util.List;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.yvdedu.hospital.entity.Login;
import com.yvdedu.hospital.entity.User;
import com.yvdedu.hospital.service.LoginService;

public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	LoginService loginService;

	
//	授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String loginName = (String) principals.getPrimaryPrincipal();
		
		//角色的集合
//		Set<String> roles = new HashSet<String>();
		Login l = new Login();
		l.setLogin(loginName);
		Login login = loginService.loginquery(l);
		List<User> user = loginService.userquery(login.getId());
		//System.out.println("----------------------账号"+user);
		
		Set<String> roles = loginService.roleName(user.get(0).getRole_id());
		//System.out.println("----------------------角色集合"+roles);
		
		//权限的集合
//		Set<String> permissions = new HashSet<String>();
		//System.out.println("-----------角色ID"+user.get(0).getRole_id());
		Set<String> permissions = loginService.url(user.get(0).getRole_id());
		//System.out.println("-----------------------------权限集合"+permissions);
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addRoles(roles);//设置角色
		authorizationInfo.addStringPermissions(permissions);//设置权限
		
		return authorizationInfo;

	}

//	身份验证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String loginName = (String) token.getPrincipal();
		Login l = new Login();
		l.setLogin(loginName);
		Login login = loginService.loginquery(l);
		
		if (login == null) {  
            throw new IncorrectCredentialsException();//没找到帐号  
        }  
  
//        if (Boolean.FALSE.equals(login.getEnable())) {  
//            throw new LockedAccountException(); //帐号锁定  
//        }  
	  
		/**
		 * 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以在此判断或自定义实现  
		 */
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(login.getLogin(), login.getPassword(),getName());
		return info;

	}
	
	@Override
	public String getName() {
		return getClass().getName();
	}

}
